package cn.zhoutingrui.pethome.system.register.controller;

import cn.zhoutingrui.pethome.base.constants.BaseConstants;
import cn.zhoutingrui.pethome.system.logininfo.domain.Logininfo;
import cn.zhoutingrui.pethome.system.logininfo.service.ILogininfoService;
import cn.zhoutingrui.pethome.system.register.service.IRegisterService;
import cn.zhoutingrui.pethome.system.shop.domain.Shop;
import cn.zhoutingrui.pethome.system.user.domain.User;
import cn.zhoutingrui.pethome.system.user.domain.Wxuser;
import cn.zhoutingrui.pethome.system.user.service.IUserService;
import cn.zhoutingrui.pethome.system.user.service.IWxuserService;
import cn.zhoutingrui.pethome.system.vcode.domain.PhoneBind;
import cn.zhoutingrui.pethome.utils.AjaxResultUtil;
import cn.zhoutingrui.pethome.utils.MD5Utils;
import cn.zhoutingrui.pethome.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/register")
@Api(value = "注册相关",description = "商家和用户注册")
public class RegisterController {
    @Autowired
    private IRegisterService registerService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @Autowired
    private IWxuserService wxuserService;
    @Autowired
    private ILogininfoService logininfoService;


    @PutMapping("/shop")
    @ApiOperation("商家注册")
    public AjaxResultUtil shop(@RequestBody Shop shop){
        try {
            registerService.shopRegister(shop);
            return AjaxResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResultUtil.fail().setMsg(e.getMessage());
        }
    }

    @PostMapping("/phone")
    @ApiOperation("手机验证码登录")
    public AjaxResultUtil phone(@RequestBody HashMap<String,String> hashMap){
        String phone = hashMap.get("phone");
        String code = hashMap.get("code");
        String o = (String) redisTemplate.opsForValue().get(phone+ BaseConstants.Suffix.STATE_PHONE);
        if (o==null){
            return AjaxResultUtil.fail().setMsg("请重新获取短信验证码");
        }
        if (!o.equals(code)){
            return AjaxResultUtil.fail().setMsg("验证码错误");
        }
        //检索当前手机号是否已注册
        Long count = userService.findByPhone(phone);
        if (count==0){
            //未注册,把信息添加到user和logininfo中
            User user = new User();
            user.setPhone(phone);
            user.setUsername(phone);
            user.setState(BaseConstants.User.STATE_ENABLE);
            userService.add(user);
        }
        return AjaxResultUtil.success();
    }

    @PostMapping("/bind")
    @ApiOperation("手机绑定账号")
    public AjaxResultUtil bind(@RequestBody PhoneBind phoneBind){
        String verifyCode = phoneBind.getVerifyCode();
        String phone = phoneBind.getPhone();
        String unionId = phoneBind.getUnionId();
        if (verifyCode==null||"".equals(verifyCode.trim()))
            return AjaxResultUtil.fail().setMsg("请输入验证码");
        Object o = redisTemplate.opsForValue().get(phone + BaseConstants.Suffix.BIND_PHONE);
        if (o==null)
            return AjaxResultUtil.fail().setMsg("请先获取验证码");
        if (!o.equals(verifyCode))
            return AjaxResultUtil.fail().setMsg("验证码错误");
        //查询当前手机号是否已在系统注册
        User userByPhone = userService.findUserByPhone(phone);
        if (userByPhone!=null){//已经注册
            //查询该账号是否已绑定微信
            Wxuser byUserId = wxuserService.findByUserId(userByPhone.getId());
            if (byUserId!=null)//已绑定微信
                return AjaxResultUtil.fail().setMsg("该手机号已绑定,请先解绑");
            else {//未绑定
                //将账号id绑定到微信上
                Wxuser byUnionid = wxuserService.findByUnionid(unionId);
                byUnionid.setUserId(userByPhone.getId());
                wxuserService.update(byUnionid);
                //调用登录接口
                Logininfo logininfo = new Logininfo();
                BeanUtils.copyProperties(userByPhone,logininfo);
                logininfo.setType(BaseConstants.Type.STATE_USER);
                logininfo.setAutoLogin(true);
                //调用登录接口,执行登录
                return logininfoService.findToLogin(logininfo);
            }
        }else {//当前手机号未注册
            User user = new User();
            user.setPhone(phoneBind.getPhone());
            String password = phoneBind.getPassword();
            String salt = StrUtils.getRandomString(128);
            String md5Password = MD5Utils.encrypByMd5(password + salt);
            user.setPassword(md5Password);
            user.setSalt(salt);
            user.setState(BaseConstants.Employee.STATE_NORMAL);
            user.setCreatetime(new Date());
            user.setUsername(phone);
            Logininfo logininfo = new Logininfo();
            BeanUtils.copyProperties(user,logininfo);
            logininfo.setDisable(BaseConstants.User.STATE_ENABLE);
            logininfo.setType(BaseConstants.Type.STATE_USER);
            logininfo.setAutoLogin(true);
            //添加用户信息到logininfo
            logininfoService.add(logininfo);
            //添加logininfo的id到用户信息中
            user.setLogininfoId(logininfo.getId());
            //添加用户信息到数据库
            userService.add(user);
            //添加用户id到wxuser
            Wxuser byUnionid = wxuserService.findByUnionid(unionId);
            byUnionid.setUserId(user.getId());
            wxuserService.update(byUnionid);
            //登录
            return logininfoService.findToLogin(logininfo);
        }

    }

}
